<template xmlns:el-col="http://www.w3.org/1999/html">
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="员工姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows"
              highlight-current-row
              v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="用户名" width="120" sortable>
			</el-table-column>
      <el-table-column prop="password" label="密码" width="150" :show-overflow-tooltip="true" sortable >
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" width="100" :show-overflow-tooltip="true" sortable >
      </el-table-column>
			<el-table-column prop="email" label="邮箱" width="220" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="80" sortable>
			</el-table-column>
			<el-table-column prop="departmentVo.name" label="所属部门" width="150" sortable>
			</el-table-column>
			<el-table-column label="操作" width="250">
				<template v-slot="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handleRole(scope.$index, scope.row)">设置角色</el-button>
        </template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="total,sizes,prev, pager, next"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="query.currentPage"
                     :page-sizes="[5, 10, 50, 100]"
                     :page-size="10"
                     :total="pageInfo.total"
                     style="float:right;">
      </el-pagination>
		</el-col>

    <el-dialog title="角色操作"
               :modal="true"
               :visible.sync="setRoleVisible"
               :close-on-click-modal="false"
               width="500px">
      <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText">
      </el-input>
      <div style="margin-top: 15px">
        <el-checkbox v-model="checkedRoles" @change="chooseAllRoles">选中全部</el-checkbox>
        <el-checkbox v-model="expandRoles" @change="expandAllRoles">展开全部</el-checkbox>
      </div>
      <el-tree
          class="filter-tree"
          :data="roles"
          show-checkbox
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps"
          :filter-node-method="filterNode"
          icon-class="el-icon-plus"
          style="margin-top: 15px;margin-bottom: 15px">
      </el-tree>

      <el-button type="primary" @click="getCheckedKeys()" :loading="setRoleLoading">
        授权
      </el-button>
    </el-dialog>

		<!--新增修改界面-->
		<el-dialog title="保存" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="username">
              <el-input v-model="addForm.username" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"  show-password auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="addForm.age" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="department">
<!--              <el-input v-model="addForm.departmentVo.name" auto-complete="off"></el-input>-->
              <el-cascader
                  v-model="path"
                  placeholder="搜索"
                  :options="department"
                  :props="{checkStrictly: true,value:'id',label:'name',children:'children'}"
                  filterable
                  clearable>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
/*
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
*/

	export default {
		data() {
			return {
        setRoleVisible:false,
        setRoleLoading:false,
        roleList:"",
        roles:[],
        expandRoles: false,
        checkedRoles: false,
        filterText: '',
        // 部门路径 数组
        path:null,
        // 所属部门
        department:[],
        // 查询体
        query:{
          currentPage:1,
          pageSize:10,
          keyword:null,
        },
        // 分页结构体
        pageInfo:{
          rows: [],
          total: 0,
        },
        // 关键字查询
				filters: {
					name: ''
				},
        // 页面加载
				listLoading: false,
        // 列表选中列
				sels: [],
        // 新增界面是否显示
				addFormVisible: false,
				addLoading: false,
				addFormRules: {
          username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
				},
				//新增界面数据
				addForm: {
          username: "",
          password: "",
          email: "",
          departmentVo: {
            id:"",
            name:"",
            path:""
          }
				},
        defaultProps: {
          children: 'child',
          label: 'name',
        },
        employeeRoleQuery:{
          ids:[],
          employeeId:null,
        }
			}
		},
    watch:{
      filterText(val) {
        this.$refs.tree.filter(val);
      },
    },
		methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      expandAllRoles(){
        if (this.expandRoles) {
          for (let i in this.$refs.tree.store.nodesMap) {
            this.$refs.tree.store.nodesMap[i].expanded = true;
          }
        } else {
          for (let j in this.$refs.tree.store.nodesMap) {
            this.$refs.tree.store.nodesMap[j].expanded = false;
          }
        }
      },
      chooseAllRoles(){
        this.roleList = "";
        // 判断按钮的状态
        if (this.checkedRoles) {
          // 设置
          this.$refs.tree.setCheckedNodes(this.roles);
          for (let i = 0; i < this.$refs.tree.getCheckedNodes().length; i++) {
            this.roleList += this.$refs.tree.getCheckedNodes()[i].id + ",";
          }
          this.roleList = this.roleList.slice(0, this.roleList.length - 1);
        } else {
          this.$refs.tree.setCheckedNodes([]);
          this.roleList = "";
        }
      },
      getCheckedKeys() {
        this.employeeRoleQuery.ids = this.$refs.tree.getCheckedNodes();
        this.setRoleLoading = true;
        this.$http.post("/employee/grantedRoleById",this.employeeRoleQuery).then(()=>{
          this.setRoleLoading = false;
          this.setRoleVisible = false;
        }).catch(()=>{
          this.setRoleLoading = false;
          this.setRoleVisible = false;
          this.$message({type:"error",message:"网络错误"})
        })
      },
      /**
       * 设置角色
       * @param index
       * @param row
       */
      handleRole(index,row){
        this.setRoleVisible = true;
        this.getRolesTree(row);
      },
      // 高级查询
      search(){
        // 定义高级查询字段
        this.query.keyword = this.filters.name;
        this.getEmployees();
      },
      // 更改页面展示数据大小
      handleSizeChange(val){
        this.query.pageSize = val;
        this.getEmployees();
      },
      // 页面跳转
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getEmployees();
			},
			// 获取分页员工列表
			getEmployees() {
        // 加载效果开启
				this.listLoading = true;
        // 查询分页员工信息
        this.$http.post("/employee",this.query).then(result=>{
          result = result.data;
          if(result.success){
            // 回显
            this.pageInfo = result.object;
            // 加载效果关闭
            this.listLoading = false;
          } else {
            this.$message({type:"error",message:result.message});
            // 加载效果关闭
            this.listLoading = false;
          }
        }).catch(error => {
          // 查询异常
          this.$message({type:"error",message:"网络错误"});
          // 加载效果关闭
          this.listLoading = false;
        })
			},
			// 删除员工
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
          // 加载效果开启
					this.listLoading = true;
					this.$http.get( "/employee/delete/"+row.id).then(result=>{
            result = result.data;
            if (result.success) {
              this.getEmployees();
            } else {
              this.$message({type:"error",message:result.message});
            }
            // 加载效果关闭
            this.listLoading = false;
          }).catch(error =>{
            this.$message({type:"error",message:error.data.message});
            // 加载效果关闭
            this.listLoading = false;
          })
				}).catch(() => {
          this.$message({type:"success",message:"已取消删除！"});
				});
			},
			// 显示编辑界面
			handleEdit: function (index, row) {
				this.clear();
        this.getTree();
        this.addFormVisible = true;
        // 请求
        this.$http.get("/employee/getById/"+row.id).then(result=>{
          result = result.data;
          if (result.success) {
            // 如果部门为空 进行处理
            console.log(result.object.departmentVo)
            if (result.object.departmentVo === null){
              result.object.departmentVo ={
                id:"",
                name:"",
                path:""
              }
            }
            console.log(result.object.departmentVo)
            // 赋值
            this.addForm = result.object;
            // 所属部门回显
            let paths = this.addForm.departmentVo.path.split("/");
            this.path = Number(paths[paths.length - 1]);
            console.log(this.path)
          } else {
            this.$message({type:"error",message:result.message});
          }
        }).catch(() => {
          this.$message({type:"error",message:"网络错误！"});
        })
			},
			// 显示新增界面
			handleAdd: function () {
        this.getTree();
        this.addFormVisible = true;
			},
			// 编辑
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
              // 针对修改所属部门 如果修改了 就需要截取，没有修改，就赋值
              let path = this.path[this.path.length-1];
              if (path){
                this.addForm.departmentVo.id = path;
              } else {
                this.addForm.departmentVo.id = this.path;
              }
              // 请求
              this.$http.put("/employee/save",this.addForm).then(result=>{
                result = result.data;
                if (result.success) {
                  // 关闭窗口
                  this.addFormVisible = false;
                  // 获取员工
                  this.getEmployees();
                  // 清空addForm
                  this.clear();
                } else {
                  this.$message({type:"error",message:result.message});
                }
              }).catch(() => {
                this.$message({type:"error",message:"网络错误！"});
              })
						}).catch(()=>{
              this.$message({type:"info",message:"已取消提交！"})
            });
					}
				});
			},
      // 批量删除选择
			selsChange: function (sels) {
				this.sels = sels;
			},
			// 批量删除
			batchRemove: function () {
				let ids = this.sels.map(item => item.id);
				this.$confirm('确认批量删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/employee/deleteBatch",ids).then(()=>{
            // 回显
            this.getEmployees();
          }).catch(error=>{
            this.$message({type:"success",message:error.data.message})
          })
          this.listLoading = false;
				}).catch(() => {
          this.$message({type:"info",message:"已取消删除！"})
				});
			},
      // 获取部门级联选择
      getTree(){
        this.$http.get("/department/tree").then(result=>{
          result = result.data;
          if(result.success){
            this.department = result.object;
          } else {
            this.$message({type:"error",message:"查询失败"+result.message})
          }
        }).catch(() => {
          this.$message({type:"error",message:"网络错误"})
        })
      },
      // 清空addForm
      clear() {
        this.path="";
        this.addForm = {
          username: "",
          password: "",
          email: "",
          departmentVo: {
            id:"",
            name: ""
          }
        }
      },
      getRolesTree(row){
        this.$http.get("/role/tree").then(async result => {
          result = result.data;
          if (result.success) {
            this.roles = result.object; // 全选加进来就失效了？？？ 待测试
            //this.$refs.tree.setCheckedKeys([1611,1612],true); // 测试
            await this.getRolesById(row.id);
            /* this.$message({message: '权限树查询成功', type: 'success'});*/
          } else {
            this.$message({message: '权限树查询失败!' + result.message, type: 'error'});
          }
        }).catch(()=>{
          this.$message({message: '网络错误!',type: 'error'});
        })
      },
      getRolesById(id){
        this.employeeRoleQuery.employeeId = id;
        this.$http.get("/employee/getRoleById/"+id).then(result=>{
          result = result.data;
          let checked = result.object;
          this.$refs.tree.setCheckedKeys(checked);
        })
      }
		},
		mounted() {
      this.clear();
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>